package com.aaa.forum.interceptor;

import com.aaa.forum.config.AppConfig;
import com.aaa.forum.model.User;
import com.aaa.forum.services.IUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器类
 */
@Component  // 添加类注解, 才能让Spring容器帮我们注入.
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private IUserService userService;

    @Value("${forum.login.url}")  // 读取配置文件中的信息
    private String loginURL;

    /**
     * 前置处理(对请求的预处理)
     * @return  true: 继续流程 <br/> false: 流程中断
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取 session 对象
        HttpSession session = request.getSession(false);
        // 2. 判断用户是否登录
        if (session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            User userSession = (User) session.getAttribute(AppConfig.USER_SESSION);
            User user = userService.selectById(userSession.getId());
            session.setAttribute(AppConfig.USER_SESSION, user);
            return true;
        }
        // 3. 校验不通过, 未登录状态, 跳转到登录页面
        // 校验配置文件中的URL是否正确
        if (!loginURL.startsWith("/")) {
            // 需要 /sign-in.html, 而不是 sign-in.html
            loginURL = '/' + loginURL;
        }
        response.sendRedirect(loginURL);    // 请求重定向
        return false;
    }
}
